"""
EventBus与HookHub桥接器
实现跨语言事件总线与Python钩子系统的集成
"""

import threading
import asyncio
from typing import Any, Dict, Optional, Callable, List
from event_bus import EventBus as CPPEventBus
from hook_hub import HookHub


class EventBusBridge:
    """
    EventBus与HookHub的桥接器
    
    该类实现了以下功能：
    1. 接收来自C++事件总线的事件
    2. 将事件转发到Python钩子系统进行进一步处理
    3. 支持同步和异步事件处理
    4. 确保线程安全性
    """
    
    def __init__(self, hook_hub: Optional[HookHub] = None, event_id_mapping: Optional[Dict[int, str]] = None) -> None:
        """
        初始化桥接器
        
        Args:
            hook_hub: HookHub实例，如果为None则创建新的实例
            event_id_mapping: C++事件ID到HookHub事件名称的映射，格式为 {event_id: event_name}
        """
        self.cpp_bus = CPPEventBus()
        self.hook_hub = hook_hub or HookHub()
        # 默认映射关系
        self._event_id_mapping = event_id_mapping or {
            0xC0: "camera_frame",
            0xC1: "data_processed",
            0xC2: "system_log"
        }
        self._running = True
        self._bridge_thread = threading.Thread(target=self._bridge_loop, daemon=True)
        self._bridge_thread.start()
        
        # 为每个事件ID注册对应的转发处理器
        for event_id in self._event_id_mapping:
            # 创建闭包来捕获事件ID
            self._register_event_handler(event_id)
        
    def _register_event_handler(self, event_id: int) -> None:
        """
        为特定事件ID注册处理器
        
        Args:
            event_id: C++事件ID
        """
        def forward_event(payload: str) -> None:
            self._forward_event_with_id(event_id, payload)
        self.cpp_bus.on(event_id, forward_event)
        
    def _bridge_loop(self) -> None:
        """
        桥接器主循环
        在独立线程中运行，负责桥接器的生命周期管理和周期性任务
        """
        try:
            last_health_check = 0
            while self._running:
                # 执行周期性任务（如健康检查、统计信息更新等）
                import time
                current_time = time.time()
                if current_time - last_health_check > 5.0:  # 每5秒执行一次健康检查
                    self._health_check()
                    last_health_check = current_time
                    
                # 短暂等待以避免忙循环
                threading.Event().wait(0.1)
        except Exception as e:
            print(f"Bridge loop error: {e}")
            
    def _health_check(self) -> None:
        """健康检查方法，可用于监控桥接器状态"""
        # 这里可以添加实际的健康检查逻辑
        # 例如：检查EventBus连接状态、HookHub状态等
        pass
    
    def register_event(self,event_id:int,event_name:str,payload:str)->None:
        """
        将特定ID的EventBus事件转发到HookHub
        
        Args:
            event_id: C++事件ID
            event_name:事件名称
            payload: 事件负载数据
        """
        if event_id not in self._event_id_mapping:
            self._event_id_mapping[event_id] = event_name
        else:
            print("event exists:",event_name)
        self._forward_event_with_id(event_id,payload)
            
    def _forward_event_with_id(self, event_id: int, payload: str) -> None:
        """
        将特定ID的EventBus事件转发到HookHub
        
        Args:
            event_id: C++事件ID
            payload: 事件负载数据
        """
        try:
            # 根据C++事件ID映射到对应的HookHub事件名称
            event_name = self._event_id_mapping.get(event_id, f"cpp_event_{event_id:x}")
            self.hook_hub.emit(event_name, payload=payload)
        except Exception as e:
            print(f"Error forwarding event to HookHub: {e}")
            
    def register_handler(self, event_name: str, handler: Callable, priority: int = 0, is_async: bool = False) -> None:
        """
        注册事件处理器到HookHub
        
        Args:
            event_name: 事件名称
            handler: 事件处理器函数
            priority: 优先级
            is_async: 是否异步处理
        """
        self.hook_hub.register(event_name, handler, priority, is_async)
        
    def emit_cpp_event(self, event_id: int, payload: str) -> None:
        """
        发送事件到C++事件总线
        
        Args:
            event_id: 事件ID
            payload: 事件负载
        """
        self.cpp_bus.emit(event_id, payload)
        
    def add_event_mapping(self, event_id: int, event_name: str) -> None:
        """
        添加新的事件ID到事件名称的映射
        
        Args:
            event_id: C++事件ID
            event_name: HookHub事件名称
        """
        if event_id not in self._event_id_mapping:
            self._event_id_mapping[event_id] = event_name
            self._register_event_handler(event_id)
        
    def shutdown(self) -> None:
        """关闭桥接器"""
        self._running = False
        self.cpp_bus.shutdown()
        if self._bridge_thread.is_alive():
            self._bridge_thread.join()